﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	Runtime
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2017/9/27 14:46:31
//========================================
using Common;
using Common.XmlHandle;
using Network.UpdateData;
using SFJDService.SocketHandle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;

namespace SFJDService
{
    public static class Runtime
    {
        /// <summary>
        /// 普通TCP/UDP/文件端口
        /// </summary>
        public const int portMsg = 65401;
        public const int portUdp = 65402;
        public const int portFile = 65403;
        /// <summary>
        /// socket消息长度
        /// </summary>
        public const int SocketLenght = Packet.BytesCount;
        /// <summary>
        /// 程序安装/升级文件/Temp文件夹/记录文件 的路径
        /// </summary>
        public static string programPath = "";
        public static string pathUpdate = null;
        public static string pathTemp = null;
        public static string pathLog = null;
        /// <summary>
        /// SFJDService.exe程序版本
        /// </summary>
        public static Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
        /// <summary>
        /// 用户数据
        /// </summary>
        public static ActiveHandler UsersOnLine = new ActiveHandler();//在线用户
        public static List<ClassConfig> users = null;//所有用户
        public static ClassConfig thisUser = null;//本机用户
        /// <summary>
        /// Xml文件是否正在同步
        /// </summary>
        public static bool handingBrigade = false;
        public static bool handingContact = false;
        /// <summary>
        /// 本机的IP地址
        /// </summary>
        //public static string myIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString();
        public static string myIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.ToString().StartsWith("192.168.")).ToString();
        //public static string myIP = "127.0.0.1";
        /// <summary>
        /// 收到/发出的文件传送任务
        /// </summary>
        internal static List<string> transportReceive = new List<string>(2);
        internal static Dictionary<Guid, List<byte>> transportReceiveBytes = new Dictionary<Guid, List<byte>>(2);
        internal static List<Guid> transportSend = new List<Guid>(2);
        /// <summary>
        /// 是否正在发送/接收文件
        /// </summary>
        public static bool onSending = false;
        public static bool onReciving = false;
        /// <summary>
        /// Socket任务字典
        /// </summary>
        public static Dictionary<int, Type> dictionary = new DictionaryInitialize().GetDictionary();
        /// <summary>
        /// 是否调试模式
        /// </summary>
        public static bool isDebugMode = false;
        /// <summary>
        /// Xml文档
        /// </summary>
        public static XmlData xmlData = null;
        public static XmlBrigade xmlBrigade = null;
        public static XmlContact xmlContact = null;
        public static XmlTemp xmlTemp = null;
        public static XmlUsersData xmlUsers = null;
        public static XmlConfig xmlConfig = null;
        public static XmlTransport xmlUpload = null;
        public static XmlTransport xmlDownload = null;
        /// <summary>
        /// 调试窗口
        /// </summary>
        public static Win_Debug win_Debug = null;

        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialize()
        {
            RegistryHelper reg = new RegistryHelper();
            //pathTemp = System.IO.Path.GetTempPath();
            pathTemp = reg.GetRegistryData("TempPath");
            pathLog = pathTemp + "SFJD\\SFJDServer.log";
            programPath = reg.GetRegistryData("RootPath");
            if(programPath == "")
            {
                programPath = Environment.CurrentDirectory;
            }
            string fileConfig = programPath + "\\Config.xml";
            string fileBrigade = programPath + "\\XmlBrigade.xml";
            string fileContact = programPath + "\\XmlContact.xml";
            string fileUsersData = programPath + "\\XmlUsersData.xml";
            string fileData = programPath + "\\Data.xml";
            string fileTemp = programPath + "\\Temp.xml";

            xmlData = new XmlData(fileData);
            xmlBrigade = new XmlBrigade(fileBrigade);
            xmlConfig = new XmlConfig(fileConfig);
            xmlContact = new XmlContact(fileContact);
            xmlUsers = new XmlUsersData(fileUsersData);
            xmlTemp = new XmlTemp(fileTemp);
            //xmlUpload = new XmlUpload(pathTemp);
            //xmlDownload = new XmlDownload(pathTemp);
            xmlUpload = new XmlTransport(Common.XmlHandle.TransportType.Upload, pathTemp);
            xmlDownload = new XmlTransport(Common.XmlHandle.TransportType.Download, pathTemp);

            thisUser = xmlConfig.GetConfig();
            users = xmlUsers.GetAllUsers();
            if(thisUser == null)
            {
                thisUser = new ClassConfig();
                thisUser.ToDefault();
            }
            pathUpdate = thisUser.InPath + "Update";
        }

        public static string TranslatePacket(Packet packet)
        {
            string nameSend = "未知", nameTarget = packet.GuidTarget.ToString();
            if(packet.GuidTarget == Guid.Empty)
            {
                nameTarget = "全体";
            }
            foreach (ClassConfig user in users)
            {
                if (user.UserGuid == packet.GuidSend)
                {
                    nameSend = user.UserName;
                }
                if (user.UserGuid == packet.GuidTarget)
                {
                    nameTarget = user.UserName;
                }
            }
            return "[" + nameSend + "][" + new IPAddress(BitConverter.GetBytes(packet.IpSend)).ToString() + "][" + nameTarget + "][" + packet.MsgLenght + "]" + packet.Message;
        }

        public static string PrintActiveUsers()
        {
            string users = string.Empty;
            foreach (ClassActive user in Runtime.UsersOnLine.activeUsers)
            {
                users += user.Name + ": " + user.Ip + ";   ";
            }
            return users;
        }

        public static void DebugWindowSwitch()
        {
            if (win_Debug == null)
            {
                win_Debug = new Win_Debug();
                win_Debug.Show();
                isDebugMode = true;
            }
            else
            {
                isDebugMode = false;
                win_Debug.Close();
                win_Debug = null;
                GC.Collect();
            }
        }

        public static void Printf(string msg)
        {
            if (isDebugMode)
            {
                //Log.ToConsole(msg);
                //DebugWindowSwitch();
                win_Debug.OutputMsg(msg);
            }
            else
            {
                Log.ToFile(pathLog, msg);
            }
        }
    }
}
